import React from 'react';
import { log } from '@/utils/log-utils';
import styles from '@/pages/watch/index.less';
import { Toast } from 'antd-mobile';
import { Col, Row } from 'antd';
import { btnSound, playSound } from '@/utils/sounds-res';
import SocketEvent from '@/service/event';
import WatchBoard from '@/pages/watch/board';
import { noDataImg } from '@/utils/images-res';
import AdvancedBtn from "@/button";
import AdvancedSpin from "@/spinner";

/**
 * 观战平台
 */
class WatchPlatform extends React.Component {

  constructor(props) {
    super(props);

    this.watchList = 'watchList';
    this.watchBoard = 'watchBoard';

    this.state = {
      loading: false,
      text: null,
      data: [],
      pageNum: 1,
      pageSize: 10,
      // 总页数
      dataTotal: 1,
      user: null,
      enemy: null,
      gameMap: null,
      isRedMove: null,
      chessBox: { show: false },
      page: this.watchList,
      roomId: null,
      battleId: null,
      emptyDataSwitch: false,
    };

    this.joinWatchRespId = 'joinWatchRespId';
    this.unRegisterServices = [];
    this.unRegisterServices.push(this.joinWatchRespId);
  }

  componentDidMount() {
    const { userId, roomId, battleId } = this.props;
    // 若有房间号，直接请求房间数据，请求成功后，进入观战棋盘(数据断连走此通道)
    if (roomId) {
      this.setState({ loading: true, text: '正在进入房间' });
      log(`用户[${userId}]请求加入观战房间[${roomId}]`);
      SocketEvent.emit(this.props.socket, 'joinWatchApi', {
        userId: userId,
        roomId: roomId,
      });
      this.setState({ roomId, battleId });
    } else {
      // 加载列表
      this.queryPkList();
    }

    // 查询用户信息(此处如果后端强制恢复对局，会导致一个内存泄露的warn)
    SocketEvent.emit(this.props.socket, 'userDetailApi', {
      userId: this.props.userId,
    }, resp => {
      log("用户详情：", resp);

      if (resp.code === 'success') {
        const {user} = resp.data;
        this.setState({ userDetail: user });
      } else {
        Toast.show('账号信息异常，请重新登录');
        this.props.goBack();
      }
    });

    // 加入观战结果监听
    SocketEvent.register('joinWatchRespApi', this.joinWatchRespId, resp => {
      log(`用户[${userId}]加入观战房间，返回：`, resp);
      this.setState({ loading: false });
      if (resp.code === 'success') {
        // 读取用户
        const { roomUser, roomEnemy, battleId } = resp.data;
        // 获取棋盘
        const currUser = roomUser.first ? roomUser : roomEnemy;
        // 获取最后落子的位置
        const chessBox = currUser.chessBox;

        this.setState({
          user: roomUser.first ? roomUser : roomEnemy,
          enemy: roomEnemy.first ? roomUser : roomEnemy,
          gameMap: currUser.gameMap,
          battleId: battleId,
          chessBox: {
            ...chessBox,
            show: currUser.stepCount !== 0,
          },
          isRedMove: currUser.isRedMove,
          // 切换到观战棋盘页面
          page: this.watchBoard,
        });
      } else {
        Toast.show(resp.msg);
        this.setState({ roomId: null });
        this.props.goBack();
      }
    });
  }

  /**
   * 查询观战数据
   */
  queryPkList = () => {
    const { pageNum, pageSize } = this.state;
    log(`开始获取观战列表, pageNum: ${pageNum} pageSize: ${pageSize}`);
    // this.setState({ loading: true, text: '正在获取数据...', emptyDataSwitch: false });
    this.setState({ emptyDataSwitch: false });
    SocketEvent.emit(this.props.socket,'watchListApi', {
      userId: this.props.userId,
      pageNum, pageSize,
    }, resp => {
      log('获取观战列表数据返回：', resp);
      this.setState({ loading: false });
      if (resp.code === 'success') {
        const { list, dataTotal } = resp.data;
        this.setState({ data: list, dataTotal, emptyDataSwitch: list.length === 0 });
      } else {
        this.setState({ emptyDataSwitch: true });
      }
    });
  };

  /**
   * 离开对战平台
   */
  handleLeavePlatform = e => {
    playSound(btnSound);
    this.props.goBack();
  };


  /**
   * 观战模式已选择好房间
   * @param e
   * @param roomId
   */
  selectedRoom = (e, roomId) => {
    playSound(btnSound);
    this.setState({ loading: true, text: '正在进入房间' });
    log(`用户[${this.props.userId}]请求获取房间[${roomId}]的观战数据`);
    SocketEvent.emit(this.props.socket,'joinWatchApi', {
      userId: this.props.userId,
      roomId: roomId,
    });
    this.setState({ roomId });
  };

  /**
   * 子页面退出
   */
  goBack = () => {
    this.setState({
      page: this.watchList,
      user: null,
      enemy: null,
      gameMap: null,
      isRedMove: null,
      chessBox: { show: false },
      roomId: null,
      data: [],
    });
    // 重新查询对战列表
    this.queryPkList();
  };

  emptyDataView = () => {
    return (
      <div className={styles.empty}>
        <img src={noDataImg} alt={''} />
        <span>暂无数据</span>
      </div>
    );
  };

  componentWillUnmount() {
    SocketEvent.unRegister(this.unRegisterServices);
  }

  /**
   * 查观战列表的视图
   */
  watchListView = () => {
    const { data, pageNum, pageSize, dataTotal, emptyDataSwitch } = this.state;
    return (
      <div className={styles.watch}>
        <div className={styles.title}>
          <div title={'icon'}/>
          <span>对战列表</span>
        </div>

        <div className={styles.content}>
          <div className={styles.list} ref={ref => this.scrollRef = ref}>
            {
              data.map((item, index) => {
                return (
                  <Row key={index} className={styles.row} onClick={e => this.selectedRoom(e, item.roomId)}>
                    <Col span={2} className={styles.colTitle}>{index + 1}.</Col>
                    <Col span={10} className={styles.colContent}>{item.userName}</Col>
                    <Col span={2} className={styles.colTitle}>:</Col>
                    <Col span={10} className={styles.colContent}>{item.enemyName}</Col>
                  </Row>
                );
              })
            }
            {/*空数据集展示*/}
            {emptyDataSwitch && this.emptyDataView()}
          </div>
          <div className={styles.floor}>
            <Row>
              <Col span={7}>
                <AdvancedBtn
                  type="normal"
                  text="上页"
                  disabled={pageNum === 1}
                  onClick={async e => {
                    playSound(btnSound);
                    if(pageNum === 1) {
                      Toast.show('已达第一页')
                    } else {
                      await this.setState({ pageNum: pageNum - 1 });
                      this.scrollRef.scrollTop = 0;
                      this.queryPkList();
                    }
                  }}
                />
              </Col>
              <Col span={1}/>
              <Col span={7}>
                <AdvancedBtn
                  type="normal"
                  text="下页"
                  disabled={(pageNum * pageSize) >= dataTotal}
                  onClick={async e => {
                    playSound(btnSound);
                    if((pageNum * pageSize) >= dataTotal) {
                      Toast.show('已达最后一页')
                    } else {
                      await this.setState({ pageNum: pageNum + 1 });
                      this.scrollRef.scrollTop = 0;
                      this.queryPkList();
                    }
                  }}
                />
              </Col>
              <Col span={1}/>
              <Col span={8}>
                <AdvancedBtn type="danger" text="离开" onClick={e => this.handleLeavePlatform(e)} />
              </Col>
            </Row>
          </div>
        </div>
        <AdvancedSpin text={this.state.text} show={this.state.loading}/>
      </div>
    );
  };

  render() {
    const { page } = this.state;
    return (
      <React.Fragment>
        {(!page || page === this.watchList) && this.watchListView()}
        {
          (page === this.watchBoard) &&
          <WatchBoard
            {...this.state}
            socket={this.props.socket}
            userId={this.props.userId}
            userDetail={this.state.userDetail}
            battleId={this.state.battleId}
            goBack={() => this.goBack()}
          />
        }
      </React.Fragment>
    );
  }
}

export default WatchPlatform;


